package com.java.business.system.permis.service;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.java.business.system.permis.bean.User;
import com.java.business.system.permis.bean.UserRole;
import com.java.business.system.permis.dao.UserMapper;
import com.java.core.utils.IdUtils;

@Transactional
@Service
public class UserService {

	@Autowired
	private UserMapper mapper;

	/**
	 * 添加用户信息
	 * 
	 * @param user
	 */
	public void add(User user) throws RuntimeException {
		user.setUserid(IdUtils.uuid());
		mapper.add(user);
	}

	/**
	 * 修改用户信息
	 * 
	 * @param user
	 * @throws RuntimeException
	 */
	public void update(User user) throws RuntimeException {
		mapper.update(user);
	}

	/**
	 * 删除用户信息
	 * 
	 * @param user
	 * @throws RuntimeException
	 */
	public void delete(User user) throws RuntimeException {
		mapper.delete(user.getUserid());
	}

	/**
	 * 设置密码
	 * 
	 * @param user
	 * @throws RuntimeException
	 */
	public void setPassword(User user) throws RuntimeException {
		mapper.setPassword(user);
	}

	/**
	 * 设置无效
	 * 
	 * @param user
	 * @throws RuntimeException
	 */
	public void setDisabled(User user) throws RuntimeException {
		mapper.setDisabled(user);
	}

	/**
	 * 设置角色
	 * 
	 * @param userid
	 * @param roleids
	 */
	public void setRoles(String userid, String[] roleids) {
		if (StringUtils.isBlank(userid) || userid.equals("0")) {
			return;
		}
		mapper.clearRoles(userid);
		for (String roleid : roleids) {
			UserRole ur = new UserRole();
			ur.setUserid(userid);
			ur.setRoleid(roleid);
			mapper.setRoles(ur);
		}
	}

	/**
	 * 设置角色
	 * 
	 * @param userid
	 * @param roleid
	 */
	public void setRole(String userid, String roleid) {
		if (StringUtils.isBlank(userid)) {
			return;
		}
		UserRole ur = new UserRole();
		ur.setUserid(userid);
		ur.setRoleid(roleid);
		mapper.setRoles(ur);
	}

	/**
	 * 移除角色
	 * 
	 * @param userid
	 * @param roleid
	 */
	public void removeRole(String userid, String roleid) {
		if (StringUtils.isBlank(userid)) {
			return;
		}
		mapper.removeRole(userid, roleid);
	}

	/**
	 * 根据用户编号获取用户信息
	 * 
	 * @param user
	 * @return
	 */
	public User getUserByUserId(String userid) {
		return mapper.getUserByUserId(userid);
	}

	/**
	 * 根据用户名获取用户信息
	 * 
	 * @param user
	 * @return
	 */
	public User getUserByUserName(String username) {
		return mapper.getUserByUserName(username);
	}

	/**
	 * 获取用户列表
	 * 
	 * @param user
	 * @return
	 */
	public List<User> getUserList(User user) {
		return mapper.getUserList(user);
	}
}
